/*
 * Copyright (C) 2007-2012 by XDEV Software, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 3.0 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
 
package xdev.db;


import java.util.ArrayList;
import java.util.List;


//TODO javadoc (class description)
public class PrefetchedResult extends Result
{
	private final Result			result;
	private final int				columnCount;
	private final List<Object[]>	data;
	private int						index	= -1;
	

	/**
	 * Constructs a {@link PrefetchedResult} that is initialized with
	 * <code>result</code>. <br>
	 * 
	 * @param result
	 *            a {@link Result} that include the data for this
	 *            {@link PrefetchedResult}
	 * 
	 */
	public PrefetchedResult(Result result) throws DBException
	{
		this.result = result;
		
		columnCount = result.getColumnCount();
		data = new ArrayList();
		
		while(result.next())
		{
			Object[] row = new Object[columnCount];
			for(int col = 0; col < columnCount; col++)
			{
				row[col] = result.getObject(col);
			}
			data.add(row);
		}
	}
	

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int getColumnCount()
	{
		return columnCount;
	}
	

	/**
	 * {@inheritDoc}
	 */
	@Override
	public ColumnMetaData getMetadata(int col)
	{
		return result.getMetadata(col);
	}
	

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean next() throws DBException
	{
		return ++index < data.size();
	}
	

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object getObject(int col) throws DBException
	{
		return data.get(index)[col];
	}
	

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int skip(int count) throws DBException
	{
		index += count;
		return count;
	}
	

	/**
	 * @since 3.2
	 */
	public void rewind()
	{
		index = -1;
	}
	

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void close() throws DBException
	{
		result.close();
		data.clear();
	}
}
